package cn.bird.storm.component.exception;

import cn.bird.exception.BusiException;
import cn.bird.exception.CoreStatusInfo;
import cn.bird.storm.component.jackson.response.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.NoSuchElementException;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 */
@Slf4j
@RestControllerAdvice
@Order(-1)
public class GlobalExceptionHandler {

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(BusiException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseResult<Object> businessException(BusiException e) {
        log.error("业务异常：{}", e.getMessage(), e);
        ResponseResult<Object> jsonResponse = new ResponseResult<>();
        jsonResponse.setRetCode(e.getCode());
        jsonResponse.setRetMsg(e.getMessage());
        jsonResponse.setData(e.getObject());
        return jsonResponse;
    }

    /**
     * 拦截optional.get()为空时的运行时异常
     */
    @ExceptionHandler(NoSuchElementException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseResult<Object> notResource(NoSuchElementException e) {
        log.error("运行时异常 {}", e.getLocalizedMessage(), e);
        return ResponseResult.byStatus(CoreStatusInfo.INTERNAL_SERVER_ERROR);
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseResult<Object> unknownException(RuntimeException e) {
        log.error("运行时异常 {}", e.getLocalizedMessage(), e);
        return ResponseResult.byStatus(CoreStatusInfo.INTERNAL_SERVER_ERROR);
    }

}
